﻿using System.Linq;
using Android.Content;

namespace Cinemacenter.Droid
{
	public class SettingsKey<T>
	{
		public string Key { get; private set; }

		readonly string _preferenceName;
		T _defaultValue;

		public SettingsKey (string key, string preferenceName, T defaultValue)
		{
			Key = key;
			_preferenceName = preferenceName;
			_defaultValue = defaultValue;
		}

		public T GetSetting (Context context)
		{
			var shared = context.GetSharedPreferences (_preferenceName, FileCreationMode.WorldReadable);
			var pair = shared.All.FirstOrDefault (x => x.Key == Key);
			return pair.Value == null ? _defaultValue : (T)pair.Value;
		}

		public SettingsKey<T> SetSetting (Context context, T val)
		{
			var shared = context.GetSharedPreferences (_preferenceName, FileCreationMode.WorldWriteable);
			var edit = shared.Edit ();
			edit.SaveObject (Key, val);
			edit.Commit ();
			return this;
		}
	}
}